
from rest_framework import serializers

from utils.models import get_child_ids
from utils.views import TreeSerializer
from oauth.models import Departments

from rest_framework.filters import SearchFilter

# 必须先继承BulkSerializerMixin，由它将只读字段id的值写回到validated_data中，才能实现更新操作

class DepartmentsSerializer(serializers.ModelSerializer):

    """
    部门管理序列化器
    """
    create_time = serializers.DateTimeField(source='gmt_create',format='%Y-%m-%d %H:%M:%S', read_only=True)
    update_time = serializers.DateTimeField(source='gmt_modified',format='%Y-%m-%d %H:%M:%S', read_only=True)
    label = serializers.CharField(source='name',required=False)
    class Meta:
        model = Departments
        exclude= ['gmt_create','gmt_modified']
    
    def update(self, instance, validated_data):
        # 验证服部门父部门不能为其本身或其子部门
        departments_id = get_child_ids(instance.id, Departments)
        if validated_data.get('pid') and validated_data.get('pid').id in departments_id:
            raise serializers.ValidationError('父部门不能为其本身或其子部门')
        return super().update(instance, validated_data)


class DepartmentsTreeSerializer(TreeSerializer):
    """
    部门数据序列化器(Element Tree)
    """
   #  create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    create_time = serializers.DateTimeField(source='gmt_create',format='%Y-%m-%d %H:%M:%S', read_only=True)
    class Meta:
        model = Departments
        exclude= ['gmt_create','gmt_modified']
        # fields = '__all__'
